export function getStorage(state, key, defaultValue) { //本地获取缓存
  return new Promise((resolve, reject) => {
    wx.getStorage({
      key: key,
      success: res => {
        state[key] = res.data;
        resolve(res.data)
      },
      fail: res => {
        state.key = defaultValue;
        reject('获取缓存失败')
      }
    })
  })

}

export function setStorage(key,vaule) {  //异步设置本地缓存
  return new Promise((resolve, reject) => {
    wx.setStorage({
      key: key,
      data: vaule,
      success: () => {
        resolve();
      },
      fail: () => {
        reject();
      }
    })
  })

}

export function throttle(fn, delay, mustRunDelay = 0) {
  let timer = null;
  let tStart;
  return function () {
    const context = this;
    const args = arguments;
    const tCurr = +new Date();
    clearTimeout(timer);
    if (!tStart) {
      tStart = tCurr;
    }
    if (mustRunDelay !== 0 && tCurr - tStart >= mustRunDelay) {
      fn.apply(context, args);
      tStart = tCurr;
    } else {
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);
    }
  };
}

export default {
  getStorage,
  setStorage,
  throttle
}
